﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms.Design;
using System.Web.UI;

namespace Org.Eurekaa.DNJ.UI.Design.Editors
{
    public class UICodeEditor : System.Drawing.Design.UITypeEditor
    {
        public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            if (context == null)
                return base.GetEditStyle(null);
            return System.Drawing.Design.UITypeEditorEditStyle.Modal;
        }

        private string GetFormattedScript(string script)
        {
            script = System.Web.HttpUtility.HtmlDecode(script).Trim();
            //script = script.Trim();            
            return script;
        }
        private string FormatScript(string script)
        {
            script = System.Web.HttpUtility.HtmlDecode(script.Trim(new char[] { ' ', '\n', '\r' }).Trim()); 
            return script;
        }

        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (context != null && provider != null)
            {
                IWindowsFormsEditorService edSrv = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
                if (edSrv != null)
                {
                    CodeEditor dialog = new CodeEditor();
                    if (value is String)
                        dialog.Value = GetFormattedScript((string)value);

                    if (edSrv.ShowDialog(dialog) == System.Windows.Forms.DialogResult.OK)
                    {
                        if (value is String)
                            value = FormatScript(dialog.Value);

                    }
                    dialog.Dispose();
                    dialog = null;
                }
            }
            return value;
        }
    }

}
